package com.etc.library.interceptors;

import com.etc.library.annotation.Auth;
import com.etc.library.util.JWTUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;
import java.util.Enumeration;

public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断是否是处理器方法对象（虚拟路径）
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //获取token
        String token = request.getHeader("authorization");
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //获取当前访问的方法对象
        Method method = handlerMethod.getMethod();

        if(method.isAnnotationPresent(Auth.class)){
            //表名该handler必须是登录后才能访问
            //校验token
            try {
                token = token.substring(7);
                JWTUtil.checkToken(token);

                request.setAttribute("userId",JWTUtil.parseToken(token).get(0));
                request.setAttribute("role",JWTUtil.parseToken(token).get(1));
            } catch (Exception e) {
                throw new RuntimeException("token无效，请重新登录");
            }
        }

        return true;
    }
}
